<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vueCDN引入组件的方式Pinia-Router-Axios</title>
    <style>
        .container {
            padding: 0;
            margin: 0;
        }

        .container .wrap {
            margin: 0 auto;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="container">
            <h1>{{ message }}</h1>
            <div class="wrap">
                <!-- 导航链接 -->
                <nav>
                    <router-link to="/">首页</router-link> |
                    <router-link to="/count">计数器</router-link> |
                    <router-link to="/user/admin">用户: admin</router-link>
                </nav>

                <!-- 路由出口 -->
                <router-view></router-view>
            </div>
        </div>
    </div>
    <script src="../lib/vue/3/vue.global.js"></script>
    <!-- 引入 Pinia -->
    <script>
        window.devtoolsApi = window.devtoolsApi || {
            setupDevtoolsPlugin: function () { }
        }
    </script>
    <script src="../lib/pinia/3/pinia.iife.js"></script>
    <!-- 引入 Vue Router (iife 版本，适用于浏览器) -->
    <script src="../lib/router/4/vue-router.global.js"></script>
    <!-- 引入 Axios -->
    <script src="../lib/axios/axios.min.js"></script>
    <script>
        const { createApp, ref } = Vue;
        const { createPinia, defineStore } = Pinia;
        const { createRouter, createWebHashHistory, RouterLink, RouterView } = VueRouter;

        const options = {
            data: function () {
                return {
                    message: 'Hello'
                }
            }
        }

        // 创建 Pinia 实例
        const pinia = createPinia();

        // 定义 store
        const useMainStore = defineStore('main', {
            state: () => ({
                count: 0,
                name: 'Pinia'
            }),
            getters: {
                doubleCount: (state) => state.count * 2
            },
            actions: {
                increment() {
                    this.count++;
                },
                decrement() {
                    this.count--;
                }
            }
        });

        // 创建 Pinia 应用
        options.mounted = function () {
            this.$store = useMainStore();
        }

        // 定义路由组件（可以用 template 字符串）
        const Home = { template: `<div><h2>首页内容</h2><p>欢迎来到首页！</p></div>` };
        const Count = {
            template: `
            <h2>{{ $store.name }} 的计数器：{{ $store.count }}</h2>
            <button @click="$store.increment()">+1</button>
            <button @click="$store.decrement()">-1</button>
            <p>双倍值: {{ $store.doubleCount }}</p>
        ` };
        const User = {
            template: `
                <div><h2>用户：{{ $route.params.id }}</h2></div>
                <h1>用户列表（Axios 获取）</h1>
                <button @click="fetchUsers" :disabled="loading">
                    {{ loading ? '加载中...' : '获取用户' }}
                </button>
                <ul v-if="users.length">
                    <li v-for="user in users" :key="user.id">
                        {{ user.name }} - {{ user.email }}
                    </li>
                </ul>
                <p v-if="error" style="color: red;">错误：{{ error }}</p>
            `,
            setup() {
                // 响应式数据
                const users = ref([]);
                const loading = ref(false);
                const error = ref('');

                // 获取用户数据
                const fetchUsers = async () => {
                    loading.value = true;
                    error.value = '';
                    try {
                        // 使用全局 axios 发起请求
                        const response = await axios.get('https://jsonplaceholder.typicode.com/users');
                        users.value = response.data;
                    } catch (err) {
                        error.value = err.message || '请求失败';
                    } finally {
                        loading.value = false;
                    }
                };

                return {
                    users,
                    loading,
                    error,
                    fetchUsers
                };
            },
            mounted() {
                console.log('当前用户ID:', this.$route.params.id);
            }
        };

        // 定义路由
        const routes = [
            { path: '/', component: Home },
            { path: '/count', component: Count },
            { path: '/user/:id', component: User }
        ];

        // 创建路由器实例
        const router = createRouter({
            history: createWebHashHistory(), // 使用 hash 模式，适合静态页面
            // history: createWebHistory(), // 使用 history 模式，需要服务器支持
            routes
        });

        const app = createApp(options);

        // 使用 Pinia 插件
        app.use(pinia);

        // 使用路由插件
        app.use(router);

        // （可选）全局注入 $store 方便模板访问（实际开发建议在 setup 中使用）
        app.config.globalProperties.$store = useMainStore();

        // 挂载
        const vm = app.mount('#app');
        // 方法一：直接修改实例的data属性
        setTimeout(() => {
            vm.message = 'Hello Vue 3!';
        }, 2000);
        // 方法二：通过$data属性修改
        setTimeout(() => {
            vm.$data.message = 'vueCDN引入组件的方式Pinia-Router-Axios';
        }, 4000);

        console.log('app', app);
        console.log('app_instance', app._instance);
        console.log('app_instance.data', app._instance.data);
    </script>
</body>